Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
What is the Java grammar that allows "new int[] {0}[0] = 1;" to compile?

I am using The Java® Language Specification Java SE 8 Edition as a reference.

Example class:

class MyClass {

  void method() {
    new int[] {0}[0] = 1;
  }

}

The code new int[] {0}[0] = 1 should be an Assignment, as index 0 of the created array is being assigned the value 1.

An Assignment is comprised of a LeftHandSide, AssignmentOperator, and an Expression. In this example, the LeftHandSide should be new int[] {0}[0].

A LeftHandSide is either an ExpressionName, FieldAccess, or ArrayAccess. In this example, the LeftHandSide should be an ArrayAccess.

The problem lies with ArrayAccess. ArrayAccess is defined as being either an ExpressionName (not the case for this example) or a PrimaryNoNewArray, and then an Expression between brackets.

The code new int[] {0} is an ArrayCreationExpression. A Primary expression is either an ArrayCreationExpression or a PrimaryNoNewArray. So to me, it seems like the second case for ArrayAccess should be Primary and not PrimaryNoNewArray.

I know the JLS doesn't have explicit grammar for everything, such as parenthesized Expressions or parenthesized LeftHandSides, but this seems to be an error. I checked the most recent spec (Java SE 17) and the grammar for ArrayAccess is unchanged.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It looks like strictly speaking, this doesn't conform with the grammar as specified. But at least, it does make sense for a compiler to allow it: the reason PrimaryNoNewArray is used instead of Primary here is so that an expression like new int[1][0] cannot be ambiguously parsed as either a 2D array or as an array access like (new int[1])[0]. If the array has an initializer like new int[]{0}[0] then the syntax is not ambiguous because this cannot be parsed as creating a 2D array.

That said, since the JLS doesn't specify that it's allowed, it could be treated as either an implementation detail or a bug in the compiler which allows it.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda